In single-threaded environments, the use of this
in constructors is normal, and expected. But in multi-threaded environments, it could
expose partially-constructed objects to other threads, and should be used with caution.
The classic example is a class with a static
list of its instances. If the constructor stores this
in the list, another
thread could access the object before it’s fully-formed. Even when the storage of this
is the last instruction in the constructor,
there’s still a danger if the class is not final
. In that case, the initialization of subclasses won’t be complete before
this
is exposed.
This rule raises an issue when this
is assigned to any globally-visible object in a constructor, and when it is passed to the method
of another object in a constructor
Noncompliant code example
public class Monument
{
public static readonly List<Monument> ALL_MONUMENTS = new List<Monument>();
// ...
public Monument(string location, ...)
{
ALL_MONUMENTS.Add(this); // Noncompliant; passed to a method of another object
this.location = location;
// ...
}
}
Exceptions
This rule ignores instances of assigning this
directly to a static
field of the same class because that case is covered
by S3010 .